package com.qyhl.webtv.module_news.news.smallvideo.detail;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.NotchSizeUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.news.CatchSmallBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBar;
import com.qyhl.webtv.commonlib.utils.view.editbar.EditBarOnClickListenerImpl;
import com.qyhl.webtv.commonlib.utils.view.video.detailvideo.QYVideoPlayer;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2018/4/23.
 */
@Route(path = ARouterPathConstant.SMALL_VIDEO_DETAIL_ACTIVITY)
public class SmallVideoDetailActivity extends BaseActivity implements SmallVideoDetailContract.SmallVideoDetailView, BaseActivity.InputListener {
    @BindView(R2.id.editbar)
    EditBar editbar;
    @BindView(R2.id.video_player)
    QYVideoPlayer videoPlayer;
    @BindView(R2.id.type)
    TextView type;
    @BindView(R2.id.comment)
    TextView commentNum;
    @BindView(R2.id.share)
    TextView share;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;

    private SmallVideoDetailPresenter mPresenter;

    @Autowired(name = "newsId")
    String newsId;

    private int commentRule;//审核模式

    private CommonAdapter commonAdapter;

    private EmptyWrapper emptyWrapper;

    private List<CatchSmallBean.Comments> mDataList;

    private int page = 1;

    private String comment, time;

    private CatchSmallBean mBean;

    private int mIndex;

    private int currentPosition = 0;
    private boolean editbarEnable = true;
    /**
     * 是否是刘海屏
     */
    private boolean isNotch;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        isNotch = NotchSizeUtil.hasNotchInScene(this);
        if (!isNotch) {
            if (Build.VERSION.SDK_INT > 19) {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
        }

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_smallvideo_detail2;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {

    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new SmallVideoDetailPresenter(this);
        initView();

    }

    @Override
    protected void setListener() {
        setListeners();
        mPresenter.count(newsId);
        mPresenter.getDetail(newsId);
    }

    /**
     * 初始化
     */
    private void initView() {
        addInputListener(this);
        loadMask.setStatus(LoadingLayout.Loading);

        mDataList = new ArrayList<>();
        //配置刷新头
        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(false);
        refresh.setDisableContentWhenLoading(true);
        refresh.setDisableContentWhenRefresh(true);

        editbar.hideCollect(true)
                .setBackground(R.color.global_black_lv1)
                .setSendTextColor(Color.WHITE);


        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);


        commonAdapter = new CommonAdapter<CatchSmallBean.Comments>(this, R.layout.news_item_small_video_comment, mDataList) {
            @Override
            protected void convert(ViewHolder holder, CatchSmallBean.Comments comments, int position) {
                holder.setText(R.id.nickName, comments.getNickName());
                holder.setText(R.id.content, comments.getContent());
                holder.setText(R.id.publish_date, DateUtils.mTranslateDate(comments.getCareateTime()));
                ImageView headIcon = holder.getView(R.id.head_icon);

                Glide.with(getApplicationContext())
                        .load(comments.getUserAvatar())
                        .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default).transform(new GlideCircleTransform(SmallVideoDetailActivity.this)))
                        .into(headIcon);
            }

        };

        emptyWrapper = new EmptyWrapper(commonAdapter);
        emptyWrapper.setEmptyView(R.layout.news_layout_smallvideo_detail_emptyview);
        recyclerView.setAdapter(emptyWrapper);

    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //刷新
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                mPresenter.getComment(page + "", "10", newsId);
            }
        });

        //加载
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                mPresenter.getComment(page + "", "10", newsId);
            }
        });

        //重载
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getDetail(newsId);
            }
        });


        editbar.setEditBarOnClickListener(new EditBarOnClickListenerImpl() {
            @Override
            public void onSend() {
                if (editbarEnable) {
                    editbarEnable = false;
                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                comment = editbar.getContent();
                                if (StringUtils.isEmpty(comment)) {
                                    Toasty.normal(SmallVideoDetailActivity.this, "评论不能为空！", Toast.LENGTH_SHORT).show();
                                    editbarEnable = true;
                                } else {
                                    String headicon = CommonUtils.getInstance().getUserLogo();
                                    String nickName = CommonUtils.getInstance().getNickName();
                                    String userName = CommonUtils.getInstance().getUserName();
                                    mPresenter.sendComment(newsId, comment, userName, nickName, headicon);
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    time = simpleDateFormat.format(new Date());
                                    hideInput();//隐藏软键盘
                                    editbar.clearContent();
                                }
                            } else {
                                Toasty.normal(SmallVideoDetailActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                                RouterManager.routerLogin(SmallVideoDetailActivity.this, 0);
                                editbarEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {
                            editbarEnable = true;
                        }
                    });

                }
            }

            @Override
            public void onShare() {
                doshare();
            }
        });

        videoPlayer.setStateListener(new QYVideoPlayer.StateListener() {
            @Override
            public void state(boolean isShow) {
                if (isShow) {
                    if (Build.VERSION.SDK_INT > 19) {
                        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
                    }
                } else {
                    if (Build.VERSION.SDK_INT > 19) {
                        getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);
                    }
                }
            }

            @Override
            public void closeRadio() {

            }
        });

        /**
         * 分享
         */
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doshare();
            }
        });

        /**
         * 类型
         */
        type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("index", mIndex+"");
                RouterManager.router(ARouterPathConstant.SMALLVIDEO,bundle);
                try {
                    currentPosition = videoPlayer.getCurrentPositionWhenPlaying();
                } catch (Exception e) {
                    currentPosition = 0;
                }

                videoPlayer.release();

            }
        });
    }

    @Override
    public void setDetail(CatchSmallBean bean) {
        refresh.finishLoadMore();
        refresh.finishRefresh();

        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        mBean = bean;

        //评论规则
        commentRule = mBean.getCommentRule();

        //设置评论数
        commentNum.setText(mBean.getCount() > 0 ? mBean.getCount() + "" : "评论");
        editbar.setCommentNum(mBean.getCount());

        if (mBean.getCount() > 0) {
            setComment(mBean.getComments(), false, false);
        } else {
            setCommentEmpty("暂无任何评论！");
        }

        //设置父栏目标志
        switch (mBean.getNewsDetail().getSectionId()) {
            case 1000006:
                type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.small_video_tag_laugh), null, null, null);
                type.setText("搞笑");
                mIndex = 1;
                break;
            case 1000007:
                type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.small_video_tag_cute), null, null, null);
                type.setText("萌物");
                mIndex = 2;
                break;
            case 1000008:
                type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.small_video_tag_sport), null, null, null);
                type.setText("运动");
                mIndex = 3;
                break;
            case 1000009:
                type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.small_video_tag_entertainment), null, null, null);
                type.setText("娱乐");
                mIndex = 4;
                break;
            case 10000010:
                type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.small_video_tag_live), null, null, null);
                type.setText("现场");
                mIndex = 5;
                break;
            default:
                type.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(this, R.drawable.small_video_tag_home), null, null, null);
                type.setText("精选");
                mIndex = 0;
                break;
        }


        ImageView imageView = new ImageView(this);
        Glide.with(this)
                .load(mBean.getNewsDetail().getCover())
                .apply(new RequestOptions().centerCrop().error(R.drawable.cover_video_default).placeholder(R.drawable.cover_video_default))
                .into(imageView);
        videoPlayer.setThumbImageView(imageView);//设置封面图

        videoPlayer.setRotateViewAuto(false);
        videoPlayer.setLockLand(true);
        videoPlayer.setMode(QYVideoPlayer.PlayMode.NORMAL);
        videoPlayer.setUp(mBean.getNewsDetail().getUrl() == null ? "" : mBean.getNewsDetail().getUrl(), true, mBean.getNewsDetail().getTitle());


        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                videoPlayer.startWindowFullscreen(SmallVideoDetailActivity.this, true, true);
            }
        });


        videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (GSYVideoManager.backFromWindowFull(SmallVideoDetailActivity.this)) {

                } else {
                    finish();
                }
            }
        });

        videoPlayer.getStartButton().performClick();//自动点击
    }

    /**
     * 无内容
     *
     * @param msg
     */
    @Override
    public void setEmpty(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();

        loadMask.setStatus(LoadingLayout.Empty);
        loadMask.setEmptyText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 加载出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();

        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();

        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 设置评论
     *
     * @param beanList
     * @param isMore
     */
    @Override
    public void setComment(List<CatchSmallBean.Comments> beanList, boolean isMore, boolean isSelf) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        refresh.setEnableLoadMore(true);

        if (isSelf) {
            mDataList.addAll(0, beanList);
        } else {
            page++;
            if (isMore) {
                mDataList.addAll(beanList);
            } else {
                mDataList.clear();
                mDataList.addAll(beanList);
            }
        }

        emptyWrapper.notifyDataSetChanged();

    }


    /**
     * 评论获取出错
     *
     * @param msg
     */
    @Override
    public void setCommentError(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        refresh.setEnableLoadMore(false);
    }

    /**
     * 无评论
     *
     * @param msg
     */
    @Override
    public void setCommentEmpty(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        refresh.setEnableLoadMore(false);
        emptyWrapper.notifyDataSetChanged();
    }

    /**
     * 评论提示
     *
     * @param msg
     */
    @Override
    public void setCommentMessage(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        refresh.setEnableLoadMore(false);
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * log
     *
     * @param msg
     */
    @Override
    public void setLog(String msg) {
        refresh.finishLoadMore();
        refresh.finishRefresh();
        Log.i("detail_smallvideo", msg);
    }

    /**
     * 评论成功
     *
     * @param msg
     */
    @Override
    public void sendSuccess(String msg) {
        editbar.changeStateDefault(this);
        if (commentRule == 1) {
            String headicon = CommonUtils.getInstance().getUserLogo();
            Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
            List<CatchSmallBean.Comments> list = new ArrayList<>();
            String nickName = CommonUtils.getInstance().getNickName();
            String userName = CommonUtils.getInstance().getUserName();
            list.add(new CatchSmallBean.Comments(Integer.valueOf(newsId), DateUtils.mTranslateDate(time), nickName, 2, userName, comment, 0, headicon));
            setComment(list, false, true);
        } else {
            Toasty.normal(this, "评论成功，等待审核！", Toast.LENGTH_SHORT).show();
        }
        editbarEnable = true;
    }

    /**
     * 评论失败
     *
     * @param msg
     */
    @Override
    public void sendError(String msg) {
        Toasty.normal(this, msg, Toast.LENGTH_SHORT).show();
        editbarEnable = true;
    }


    /**
     * 分享
     */
    private void doshare() {
        MPermissionUtils.requestPermissionsResult(SmallVideoDetailActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
            @Override
            public void onPermissionGranted() {
                MShareBoard shareBoard = new MShareBoard(SmallVideoDetailActivity.this, newsId, mBean.getNewsDetail().getTitle(), mBean.getNewsDetail().getCover(), "", 4, true);
                shareBoard.showPopupWindow();
            }

            @Override
            public void onPermissionDenied() {
                MPermissionUtils.showTipsDialog(SmallVideoDetailActivity.this);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                if (editbar.getType() == EditBar.TYPE_SEND) {//判断是否是输入状态，是则返回初始状态，否则退出
                    editbar.changeStateDefault(this);
                    return true;
                } else if (GSYVideoManager.backFromWindowFull(this)) {
                    return true;
                } else {
                    finish();
                }
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("小视频详情");
        MobclickAgent.onResume(this);
        if (currentPosition != 0) {
            videoPlayer.setSeekOnStart(currentPosition);
            videoPlayer.startPlayLogic();
        } else {
            videoPlayer.onVideoResume();
        }

    }

    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("小视频详情");
        MobclickAgent.onPause(this);
        videoPlayer.onVideoPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoPlayer.release();
    }



    @Override
    public void showkeyboard() {

    }

    @Override
    public void hideKeyboard() {
        editbar.changeStateDefault(this);
    }
}
